<template>
  <el-dialog class="export-modal" :visible.sync="isShow" :before-close="handleCancelModal" :close-on-click-modal="false" :show-close="false" width="380px">
    <div slot="title">
      <div style="margin-bottom: 5px;font-size: 14px" class="color-info">导出的数据为勾选的商品数据，若不勾选则默认导出所有筛选出来的数据</div>
      <div style="display: flex;line-height: 32px">
        <div>
          <el-checkbox v-model="checkedAll" :indeterminate="isIndeterminate" :disabled="isSubmit" @change="handleCheckedAll">全选</el-checkbox>
        </div>
        <div style="flex-grow: 1; text-align: right">导出数据列设置</div>
      </div>
    </div>
    <div v-loading="isSubmit">
      <!-- 数据表单 -->
      <div style="height: 360px;overflow-y: scroll">
        <el-checkbox-group v-model="exportFields">
          <div v-for="(item, index) in fields" :key="index" @change="handleCheckedField(index)">
            <el-checkbox :label="item.name" :disabled="item.disabled">{{ item.name }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>
    <!-- 提交按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: center; display: flex; justify-content: space-between">
      <el-button size="small" :disabled="isSubmit" @click="handleCancelModal">取 消</el-button>
      <el-button type="primary" size="small" :loading="isSubmit" @click="handleSubmitForm">导 出</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'
import { fileUrl, imageBase64 } from '@/utils/tools'

export default {
  name: 'Export',
  props: {
    'isShow': { type: Boolean, default: true },
    'fieldList': { type: Array, default: null },
    'dataList': { type: Array, default: null }
  },
  data: function() {
    return {
      isSubmit: false,
      checkedAll: false,
      isIndeterminate: false,
      exportFields: [],
      fields: [
        { name: '图片（勾选后耗时较久）', key: 'base64', width: 22, checked: false },
        { name: '聚星字号', key: 'goods.goods_name', width: 30, checked: false },
        { name: '标号', key: 'goods.goods_code', width: 15, checked: false },
        { name: '参与出价次数', key: 'bid_goods_count', width: 15, checked: false },
        { name: '参与投标人数', key: 'bid_user_count', width: 15, checked: false },
        { name: '底价', key: 'goods.label_price', width: 15, checked: false },
        { name: '最高出价', key: 'max_price', width: 15, checked: false },
        { name: '最低出价', key: 'min_price', width: 15, checked: false },
        { name: '货主', key: 'supplier', width: 15, checked: false },
        { name: '上架时间', key: 'goods.released_at', width: 20, checked: false },
        { name: '标品介绍', key: 'goods.description', width: 30, checked: false },
        { name: '片数数量', key: 'goods.stock', width: 15, checked: false },
        { name: '重量', key: 'goods.weight', width: 15, checked: false },
        { name: '成本价', key: 'goods.cost_price', width: 15, checked: false },
        { name: '备注信息', key: 'goods.remarks', width: 20, checked: false }
      ]
    }
  },
  mounted: function() {
    if (this.fieldList) {
      this.exportFields = this.fieldList
      // 设置全选状态
      this.handleCheckedField(null)
      for (let i = 0; i < this.fields.length; i++) {
        this.fields[i].checked = (!this.fields[i].disabled && this.exportFields.indexOf(this.fields[i].name) >= 0)
      }
    }
  },
  methods: {
    handleSubmitForm() {
      if (this.exportFields.length > 0) {
        this.isSubmit = true
        localStorage.setItem('export-goods-fields', JSON.stringify(this.exportFields))
        if (this.fields[0].checked) {
          let schedule = 0
          for (let i = 0; i < this.dataList.length; i++) {
            try {
              const cover = this.completionFile(this.dataList[i]['goods']['cover'])
              if (cover) {
                imageBase64(cover).then(base64 => {
                  schedule += 1
                  this.dataList[i].base64 = base64
                  if (schedule === this.dataList.length) {
                    this.exportExcel(this.dataList)
                  }
                })
              } else {
                schedule += 1
                this.dataList[i].base64 = null
                if (schedule === this.dataList.length) {
                  this.exportExcel(this.dataList)
                }
              }
            } catch (err) {
              schedule += 1
              this.dataList[i].base64 = null
              if (schedule === this.dataList.length) {
                this.exportExcel(this.dataList)
              }
            }
          }
        } else {
          this.exportExcel(this.dataList)
        }
      }
    },
    handleCheckedAll(isAll) {
      const selected = []
      for (let i = 0; i < this.fields.length; i++) {
        this.fields[i].checked = isAll
        selected.push(this.fields[i]['name'])
      }
      this.exportFields = isAll ? selected : []
      this.isIndeterminate = false
    },
    handleCheckedField(index = null) {
      const checkedAll = this.exportFields.length
      this.checkedAll = checkedAll === this.fields.length
      this.isIndeterminate = checkedAll > 0 && checkedAll < this.fields.length
      if (index !== null) {
        this.fields[index]['checked'] = !this.fields[index]['checked']
      }
    },
    // 导出数据
    exportExcel(data) {
      console.log(data)
      if (data.length <= 0) {
        this.isSubmit = false
        this.$message.warning('没有数据可供导出'); return false
      }
      try {
        const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
        const workbook = new Workbook()
        const sheet = workbook.addWorksheet('出价列表', {
          pageSetup: { verticalCentered: true, horizontalCentered: true }
        })
        // 设置默认行高
        sheet.properties.defaultRowHeight = 20
        // 列属性设置
        const columns = []
        for (let i = 0; i < this.fields.length; i++) {
          const item = this.fields[i]
          if (item.checked && !item.disabled) {
            // 设置列属性
            columns.push({ header: item.name, key: item.key, width: item.width, style: { alignment: { vertical: 'middle', horizontal: 'left' }}})
          }
        }
        sheet.columns = columns
        // 填充数据
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          const row = {}
          for (let k = 0; k < columns.length; k++) {
            if (columns[k].key === 'base64' && item['base64']) {
              // 商品图片
              sheet.addImage(workbook.addImage({
                base64: item.base64,
                extension: 'jpg'
              }), {
                tl: { col: 0, row: (i + 1) + 0.1 },
                br: { col: 1, row: (i + 2) },
                editAs: 'oneCell'
              })
            } else if (columns[k].key.indexOf('goods.') === 0) {
              row[columns[k].key] = item.goods[columns[k].key.replace('goods.', '')]
            } else if (columns[k].key === 'supplier') {
              row[columns[k].key] = item.goods.supplier && item.goods.supplier.name
            } else {
              row[columns[k].key] = item[columns[k].key]
            }
          }
          sheet.addRow(row)
          if (this.fields[0].checked) {
            sheet.getRow(i + 2).height = 100
          }
        }
        // 设置文件名称
        workbook.xlsx.writeBuffer().then(data => {
          const blob = new Blob([data], { type: EXCEL_TYPE })
          saveAs(blob, '投标数据.xlsx')
          this.isSubmit = false
          this.handleCancelModal()
        })
      } catch (err) {
        console.log(err)
        this.isSubmit = false
      }
    },
    // 取消弹出框
    handleCancelModal(refresh = false) {
      this.$emit('on-cancel-modal', 'showExport', refresh)
    },
    // 处理文件
    completionFile(file) {
      return fileUrl(file.path)
    }
  }
}
</script>

<style lang="scss">
.export-modal {
  .el-form-item {
    margin-bottom: 6px;
  }
  .el-dialog__body {
    padding: 5px 20px;
  }
  .el-transfer-panel__header, .el-transfer-panel__header, .el-checkbox {
    height: 34px !important;
    line-height: 34px !important;
    .el-checkbox__label {
      font-size: 14px !important;
    }
  }
  .el-transfer__buttons {
    padding: 0 10px !important;
    button {
      padding: 5px 15px;
    }
  }
}
</style>
